package jsu.blogger.controller;

import jakarta.servlet.http.HttpServletRequest;
import jsu.blogger.filter.DataFilter;
import jsu.blogger.pojo.*;
import jsu.blogger.service.impl.GetUserDataServiceImpl;
import jsu.blogger.util.ReturnResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class GetUserDataController {
    @Autowired
    private GetUserDataServiceImpl getUserDataServiceImpl;
    private static final Logger log = LoggerFactory.getLogger(DataFilter.class);

    @PostMapping("/getUsername")
    public Result getUsername(HttpServletRequest request){
        Result result= ReturnResultUtil.failure("获取用户名失败，请重新登录");
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        // 安全获取 userId
        Object userIdObj = map.get("userId");
        Long userId = null;

        userId = getaLong(userIdObj, userId);
        if(userId!=null){
            //System.out.println(userId);
            String username;
            username= getUserDataServiceImpl.getUsernameByUserId(userId);

            if(username!=null){
                Map<String,Object> reMap=new HashMap<>();
                reMap.put("username",username);
                result=ReturnResultUtil.success(reMap);
            }
        }

        return result;
    }
    @PostMapping("/getOtherUserData")
    public Result getOtherUserData(HttpServletRequest request){
        Result result= ReturnResultUtil.failure("获取用户名失败，请重新登录");
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        // 安全获取 userId
        Object userIdObj = map.get("userId");
        Long userId = null;
        userId = getaLong(userIdObj, userId);
        if(userId!=null){
            UserStats userData=getUserDataServiceImpl.getOtherUserDataByUserId(userId);
            result=ReturnResultUtil.success(userData);
        }
        return result;
    }

    @PostMapping("/getUserAvatar")
    public Result getUserAvatar(HttpServletRequest request){
        Result result=ReturnResultUtil.failure("获取头像失败");Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        // 安全获取 userId
        Object userIdObj = map.get("userId");
        Long userId = null;

        userId = getaLong(userIdObj, userId);
        if(userId!=null){
            File userAvatar=getUserDataServiceImpl.getUserAvatar(userId);
            //System.out.println(userAvatar);
            if(userAvatar!=null){
                try{
                    String imgType="data:image/"+this.getFileExtension(userAvatar)+";";
                    // 将文件内容读取为字节数组
                    byte[] fileContent = Files.readAllBytes(userAvatar.toPath());
                    // 将字节数组编码为 Base64 字符串
                    String base64String = Base64.getEncoder().encodeToString(fileContent);
                    Map<String,Object> reMap=new HashMap<>();
                    reMap.put("imgType",imgType);
                    reMap.put("userAvatar",base64String);
                    result=ReturnResultUtil.success(reMap);
                } catch (IOException e) {
                    log.error(String.valueOf(e));
                }
            }
        }
        return result;
    }

    //获得关注列表，使用分页查询
    @PostMapping("/getUserFollowing")
    public Result getUserFollowing(HttpServletRequest request){
        Result result=ReturnResultUtil.failure("未知错误");
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        // 安全获取 userId
        Object userIdObj = map.get("userId");
        Long userId = null;

        userId = getaLong(userIdObj, userId);
        int currentPage= (int) map.get("currentPage");
        int pageSize= (int) map.get("pageSize");

        //System.out.println("currentPage:"+currentPage+" pageSize:"+pageSize);
        List<Users> resultList=getUserDataServiceImpl.getUserFollowingList(userId,currentPage,pageSize);
        result=ReturnResultUtil.success(resultList);
        return result;
    }

    @PostMapping("/getFavorites")
    public Result getFavorites(HttpServletRequest request){
        Result result=ReturnResultUtil.failure("未知错误");
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        // 安全获取 userId
        Object userIdObj = map.get("userId");
        Long userId = null;

        userId = getaLong(userIdObj, userId);

        List<UserFolder> reList=getUserDataServiceImpl.getUserFolderList(userId);
        if(reList!=null){
            result=ReturnResultUtil.success(reList);
        }
        return result;
    }

    @PostMapping("/getChooseInterests")
    public Result getAllChooseInterests(HttpServletRequest request){
        Result result=ReturnResultUtil.failure("未知错误");
        List<Tag> tags=getUserDataServiceImpl.getInterestTags();
        result=ReturnResultUtil.success(tags);
        return result;
    }

    @PostMapping("/getUserInterest")
    public Result getUserInterest(HttpServletRequest request){
        Result result=ReturnResultUtil.failure("未知错误");
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        Object userIdObj = map.get("userId");
        Long userId = null;
        userId = getaLong(userIdObj, userId);
        List<Tag> tags=getUserDataServiceImpl.getUserInterestTagList(userId);
        result=ReturnResultUtil.success(tags);
        return result;
    }

    @PostMapping("/getUserPosts")
    public Result getUserPosts(HttpServletRequest request){
        Result result=ReturnResultUtil.failure("未知错误");
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        Object userIdObj = map.get("userId");
        Long userId = null;
        userId = getaLong(userIdObj, userId);
        int currentPage= (int) map.get("currentPage");
        int pageSize= (int) map.get("pageSize");
        List<Post> posts=getUserDataServiceImpl.getPostsPageByUserId(userId,currentPage,pageSize);
        result=ReturnResultUtil.success(posts);
        return result;
    }

    private Long getaLong(Object userIdObj, Long userId) {
        if (userIdObj instanceof Integer) {
            // 如果 userId 是 Integer 类型
            userId = ((Integer) userIdObj).longValue();
        } else if (userIdObj instanceof Long) {
            // 如果 userId 是 Long 类型
            userId = (Long) userIdObj;
        } else {
            System.out.println("userId 类型不匹配: " + userIdObj.getClass().getName());
        }
        return userId;
    }
    private String getFileExtension(File file) {
        // 确保传入的是有效的文件对象
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("文件不存在或无效");
        }
        // 获取文件名
        String fileName = file.getName();

        // 找到最后一个点的位置
        int lastDotIndex = fileName.lastIndexOf('.');

        // 如果没有点，返回空字符串
        if (lastDotIndex == -1) {
            return "";
        }
        // 提取后缀名并转换为小写
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }

    @PostMapping("/getEmail")
    public Result getEmail(HttpServletRequest request){
        Result result= ReturnResultUtil.failure("获取用户邮箱失败，请重新登录");
        Map<String,Object> map = (Map<String, Object>) request.getAttribute("requestBody");
        // 安全获取 userId
        Object userIdObj = map.get("userId");
        Long userId = null;

        userId = getaLong(userIdObj, userId);
        if(userId!=null){
            //System.out.println(userId);
            String email;
            email= getUserDataServiceImpl.getEmailByUserId(userId);

            if(email!=null){
                Map<String,Object> reMap=new HashMap<>();
                reMap.put("email",email);
                result=ReturnResultUtil.success(reMap);
            }
        }

        return result;
    }

}
